<?php
defined ( 'BASEPATH' ) or exit ( 'No direct script access allowed' );
/**
 * 提现管理
 * @author chaituan@126.com
 */
use EasyWeChat\Foundation\Application;
class Withdraw extends AdminCommon {
	
	public function __construct() {
		parent::__construct ();
		$this->load->model(array('admin/Earnings_model'=>'do'));
	}
	
	public function index() {
		$this->load->view ('admin/withdraw/index');
	}
	
	function lists(){
		$name = Gets('name');
		$page = Gets('page','checkid');$limit = Gets('limit','checkid');
		$total = Gets('total','num');
		$where = $name?"earnings.cid=0 and earnings.state=1 and user.nicknames like '%$name%'":'earnings.cid=0 and earnings.state=1';
		$data = $this->do->getItems_join (array('user' => "user.id=earnings.uid+left"),$where,'earnings.*,user.nicknames','earnings.id desc',$page,$limit,$total);
		$find = Gets('find');
		if(($name&&$find)||!$total){
			$total = $this->do->count;
		}
		f_ajax_lists($total, $data);
	}
	
	function sh_ok(){
		$id = Gets('id');
		$uid = Gets('uid','num');
		$this->load->model('admin/User_model');
		$user = $this->User_model->getItem(array('id'=>$uid),'openid');
		$item = $this->do->getItem(array('id'=>$id),'money');
		$options = ['app_id'=>WX_APPID,'secret'=>WX_APPSecret,'payment' => ['merchant_id'=> WX_MCHID,'key'=> WX_KEY,'cert_path'=> SSLCERT_PATH,'key_path'=> SSLKEY_PATH]];
		$app = new Application($options);
		$merchantPay = $app->merchant_pay;
		
		$merchantPayData = [
			'partner_trade_no' => order_trade_no(), 
			'openid' => $user['openid'], 
			'check_name' => 'NO_CHECK', 
			'amount' => $item['money'] * 100,
			'desc' => '提现',
			'spbill_create_ip' => $this->input->ip_address()
		];
		$result = $merchantPay->send($merchantPayData);
		if($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS'){
			$this->do->updates(array('state'=>2),"id=$id");
			AjaxResult_ok();
		}else{
			AjaxResult_error($result->return_msg);
		}
	}
	
	function sh_no(){
		$id = Gets('id');
		$result = $this->do->updates(array('state'=>3),"id=$id");
		is_AjaxResult($result);
	}
	
	function del() {
		$id = Gets ('id','checkid');
		$result = $this->do->deletes(array('id'=>$id));
		is_AjaxResult($result);
	}
}
